declare var $:any
var OSS = require('ali-oss')
import Bus from './bus'
import store from '../../vuex'
const aliupload=()=>{
    /**声明 */
    var client = new OSS.Wrapper({
        /* DXL */
        // region: 'oss-cn-beijing',
        // accessKeyId: 'LTAIOZT53Uu0ykZO',
        // accessKeySecret: 'TYxjx2Icu7zjbxQ7LstQewJ6ZlLMZR',
        // bucket: 'sinostoragedev1'
        /* sino */
        region: 'oss-cn-hangzhou',
        secure:true,
        accessKeyId: 'LTAIy6GjqJzCNtlD',
        accessKeySecret: '8BZ2CxuNHmTtKQoZSChf2SgeskdZFf',
        bucket: store.state.ossBucket

    })

    /**上传图片**/
    var upload = async function (selectedFile, nameimg) {
        const file = selectedFile;
        const name = nameimg;
        var type = name.substring(name.lastIndexOf('.') + 1);
        var storeAs = "upload/" + getUuid() + '.' + type;
        try {
            return await client.multipartUpload(storeAs, file,
                {
                    progress: progress
                })
        } catch (error) {
            console.log(error);
        }
    };
    /**上传图片流**/
    var uploadStream = function (urlData, cb) {
        console.log('urlData',urlData)
        function convertBase64UrlToBlob(urlData) {
            var bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
            //处理异常,将ascii码小于0的转换为大于0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
              ia[i] = bytes.charCodeAt(i);
            }

            return new Blob([ab], { type: "image/png" });
          }
        var blob=convertBase64UrlToBlob(urlData);
        if (blob.size > 0) {
            // blob转arrayBuffer
            var reader = new FileReader();
            reader.readAsArrayBuffer(blob);
            reader.onload = (e:any)=>{
              // 文件名
              var storeAs = 'avatar/'+getUuid()+'.'+blob.type.split('/')[1];
              // arrayBuffer转Buffer
              var buffer = new OSS.Buffer(e.target.result);
              // 上传
              client
                .put(storeAs, buffer)
                .then(result => {
                    cb(result);
                })
                .catch(err => {
                  console.log(err);
                });

            };
          }
    };
    /**上传进度 */
    var progress = function (p) {
        return function (done) {
            Bus.$emit('progress',Math.round(p*100))
            done();
        }
    };

    /**重命名 */
    // var guidGenerate = function() {
    //     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    //       var r = Math.random() * 16 | 0,
    //         v = c == 'x' ? r : (r & 0x3 | 0x8);
    //       return v.toString(16);
    //     }).toUpperCase();
    //   }

    var getUuid = function () {
        var len = 32; //32长度
        var radix = 16; //16进制
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }

    /**导出方法 */
    return {
        upload: upload,
        uploadStream: uploadStream,
        progress: progress
    };
};


export  default aliupload
